package com.docMan.utils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.docMan.bean.UpdateDirRunnable;
import com.docMan.bean.UpdateDiskRunnable;
import com.docMan.dao.pojo.DocDirectory;
import com.docMan.dao.pojo.DocDisc;
import com.docMan.service.DocDirectoryService;
import com.docMan.service.DocDiscService;

@Component
public class DocDirectoryUpdate {
	private static DocDirectoryService docDirectoryService;
	private static DocDiscService docDiscService;
	private static FileIndexService fileIndexService = FileIndexService.getInstance();
	@Autowired
	public void setDocDiscService(DocDiscService docDiscService) {
		this.docDiscService = docDiscService;
	}

	@Autowired
	public void setDocDirectoryService(DocDirectoryService docDirectoryService) {
		this.docDirectoryService = docDirectoryService;
	}

	/**
	 * 在创建文件时 对文件路径上的所有文件夹和网盘的信息进行更新
	 * 
	 * @param fileSizes
	 * @param id
	 * @param type
	 *            FinalConfig.FILE_IN_DIRECTORY
	 */
	public static void updateParentsDirectoryWhenAddFiles(List<String> fileSizes,
			int id, int type) {
		double directoryFileSize = 0.0;
		for (String string : fileSizes) {
			directoryFileSize += getFileLarge(string);
		}
		// 上传文件到文件夹
		if (type == FinalConfig.FILE_IN_DIRECTORY) {
			DocDirectory docDirectory = docDirectoryService.getById(id);
			fileIndexService.updateDirectory(new UpdateDirRunnable(id,
					fileSizes.size(), 0, directoryFileSize));
			String pathId = docDirectory.getPath();
			String[] ids = pathId.split("/");
			if (ids.length >= 2) {
				fileIndexService.updateDisk(new UpdateDiskRunnable(Integer
						.parseInt(ids[0]), directoryFileSize));
				for (int i = 1; i < ids.length; i++) {
					fileIndexService.updateDirectory(new UpdateDirRunnable(
							Integer.parseInt(ids[i]), directoryFileSize));
				}
			}
		} else {// 上传文件到网盘下
			DocDisc docDisc = docDiscService.getById(id);
			docDisc.setFileCount(null == docDisc.getFileCount() ? fileSizes
					.size() : (docDisc.getFileCount() + fileSizes.size()));
			docDisc.setLarge(null == docDisc.getLarge() ? directoryFileSize
					: (docDisc.getLarge() + directoryFileSize));
			fileIndexService.updateDisk(new UpdateDiskRunnable(id,
					directoryFileSize, fileSizes.size()));
		}
	}
	
	/**
	 * 获取文件的大小
	 * 
	 * @param fileSize
	 * @return
	 */
	private static double getFileLarge(String fileSize) {
		if (fileSize.endsWith(FinalConfig.SIZE_MB)) {
			return new Double(fileSize.replace(FinalConfig.SIZE_MB, ""));
		} else {
			double size = Double.parseDouble(fileSize.replace(
					FinalConfig.SIZE_KB, "")) / 1024;
			return size;
		}
	}
}
